package com.wenboit.initproject.controller;

import com.wenboit.initproject.pojo.entity.User;
import com.wenboit.initproject.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * (UserController). 
 *
 * @author 汪文波(Wang Wenbo) wenboit@163.com
 * @notes Create on 2021-12-12 20:51
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public Page<User> getAll(@RequestParam(name = "pageNum", defaultValue = "0")int pageNum,
                             @RequestParam(name = "pageSize", defaultValue = "5")int pageSize,
                             @RequestParam(name = "sort", defaultValue = "id", required = false)String sort){
        log.info("get /user/");
        PageRequest of = PageRequest.of(pageNum, pageSize, Sort.Direction.ASC, sort);
        Page<User> list = userService.findAll(of);

       return list;
    }

    @PostMapping("/login")
    public String login(User user){
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(user.getName(), user.getPassword()));
            log.info("欢迎\"{}\",登录成功！", user.getName());
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e){
            log.info("登录失败！ {}", e.getMessage());
        } catch (IncorrectCredentialsException e){
            log.info("登录失败！ {}", e.getMessage());
        }

        return "redirect:/login.jsp";
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return "redirect:/login.jsp";
    }

}
